package gro.ecorrdata.edata.util.token;

import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import gro.ecorrdata.edata.controller.UserController;
import gro.ecorrdata.edata.util.MyUtil;

@Component
public class MySQLTokenHelp implements TokenHelper {

    public static final int TOKEN_EXPIRES_SECOND = 1800;
    
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public TokenModel create(Integer id, Long ip) {
        String token = UUID.randomUUID().toString().replace("-", "");

        // 获取用户信息
        String sql5 = "select id,role_id,username,email,create_time,FROM_UNIXTIME(login_time, '%Y-%m-%d %T') as lastTime,login_ip as lastIp,status from admin_user where id=?";
        Map<String, Object> userInfo = jdbcTemplate.queryForMap(sql5, id);

        String sql1 = "select count(*) as loginNum from login_note where userid=?";
        Map<String, Object> loginNumMap = jdbcTemplate.queryForMap(sql1, id);
        Integer loginNum = Integer.parseInt(loginNumMap.get("loginNum").toString());

        String sql2 = "select name from admin_role where id=?";
        Integer role_id = Integer.parseInt(userInfo.get("role_id").toString());
        Map<String, Object> RoleNameMap = jdbcTemplate.queryForMap(sql2, role_id);

        String rolename = RoleNameMap.get("name").toString();

        TokenModel mode = new TokenModel(id,
            token,
            loginNum,
            MyUtil.numToIp((Long) userInfo.get("lastIp")),
            userInfo.get("lastTime").toString(),
            userInfo.get("username").toString(),
            rolename
        );

        Long exptime = (Long) (System.currentTimeMillis()/1000);
        String sql = "INSERT INTO login_note(`userid`,`ip`,`time`,`token`,`exptime`) VALUES(?,?,?,?,?)";
        Object args[] = {id, ip, exptime, token, exptime};
        Integer temp = jdbcTemplate.update(sql, args);

        // 更新最近登录时间与ip
        String sql3 = "update admin_user set `login_time`=?, `login_ip`=? where id=?";
        Object args2[] = {exptime, ip, id};
        jdbcTemplate.update(sql3, args2);
        
        if (temp > 0) {
            System.out.println("登陆成功！");
		}else{
            mode.setUserId(0);
            System.out.println("登陆失败");
        }
        
        return mode;
    }

    @Override
    public boolean check(TokenModel model) {
        boolean result = false;
        if(model != null) {
            Integer userId = model.getUserId();
            String token = model.getToken();
            String sql = "select id, userid, token, exptime from login_note where token=?";
            
            try {
                Map<String, Object> loginNote  = jdbcTemplate.queryForMap(sql, token);
                Integer loginUserId = (Integer) loginNote.get("userid");
                Integer loginExptime = (Integer) loginNote.get("exptime");
                
                int now = (int) (System.currentTimeMillis()/1000);
                if (userId==loginUserId && (now-loginExptime) < TOKEN_EXPIRES_SECOND) {
                    jdbcTemplate.update("update login_note set exptime="+now+" where token='"+token+"'");
                    result = true;
                }
            } catch (Exception e) {
                e.printStackTrace();
                result = false;
            }
        }
        return result;
    }

    @Override
    public boolean delete(String token) {
        boolean result = false;

        String sql = "update login_note set `exptime`=0 where `token`=?";
        Integer temp = jdbcTemplate.update(sql, token);

        if (temp > 0) {
            System.out.println("退出成功！");
            result = true;
		}else{
            System.out.println("退出失败");
        }

        return result;
    }

    @Override
    public TokenModel get(String authStr) {
        TokenModel model = null;
        if(StringUtils.isNotEmpty(authStr)) {
            String[] modelArr = authStr.split("-");
            if(modelArr.length == 2) {
                int userId = Integer.parseInt(modelArr[0]);
                String token = modelArr[1];
                model = new TokenModel(userId, token);
            }
        }
        return model;
    }
}
